<template>
  <div>
    <el-button type="primary" @click="handleAdd"> 添加教师</el-button>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="name" label="姓名" width="180" />
      <el-table-column prop="subject" label="科目" width="180" />
      <el-table-column prop="contact" label="联系方式" width="180" />
      <el-table-column prop="email" label="邮箱" width="180" />
    </el-table>

    <el-dialog v-model="dialogVisible" title="添加教师">
      <el-form ref="addFormRef" :model="addForm" :rules="rules" label-width="80px" class="ruleForm" status-icon>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name"/>
        </el-form-item>
        <el-form-item label="科目" prop="subject">
          <el-input v-model="addForm.subject"/>
        </el-form-item>
        <el-form-item label="联系方式" prop="contact">
          <el-input v-model="addForm.contact"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import axios from "axios";

const tableData = ref([]);
const dialogVisible = ref(false);
const addFormRef = ref();
const addForm = reactive({
  name: "",
  subject: "",
  contact: "",
  email: ""
});
const rules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  subject: [{ required: true, message: '请输入科目', trigger: 'blur' }],
  contact: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }]
});

const getTeacherList = async () => {
  try {
    let res = await axios.get('http://localhost:8000/adminapi/teachers');
    tableData.value = res.data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

const handleAdd = () => {
  dialogVisible.value = true;
}

const handleAddConfirm = () => {
  addFormRef.value.validate(async (valid) => {
    if (valid) {
      dialogVisible.value = false;
      await axios.post('http://localhost:8000/adminapi/teachers', addForm);
      await getTeacherList();
      addForm.name = "";
      addForm.subject = "";
      addForm.contact = "";
      addForm.email = "";
    } else {
      console.log('Validation failed');
    }
  });
}

onMounted(() => {
  getTeacherList();
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
